////
////  CDPushService.swift
////  CandyDate
////
////  Created by zolobdz on 2017/10/19.
////  Copyright © 2017年 HeChao. All rights reserved.
////
//
//import Foundation
//import UIKit
//import UserNotifications
////import J
//
///*
//    unreadCount 说明
//
//    app的红点的未读数量由im和jpush的控制
//    jpush的红点未读数计算规则如下：
//    1.app在前台:
//    收到后调用(jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent)加1，并保存到本地
//    2.app在后台:
//    不计数，不管理！
//    3.当刷新过通讯录后未读数全部换成通讯录接口中“新的好友”和“我的邀请”的未读数的总和，然后保存到本地
// */
//
//
//class CDPushService : NSObject{
//
//    static let shared = CDPushService()
//    private override init() {}
//
//    lazy var unreadCount = 0 // 极光消息未读数
//
//    lazy var preChatUserID = "" // 聊天推送用户id
//    lazy var preUserInfo = [String:AnyObject]()
//
//    func startService(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?,delegate: AppDelegate) {
//        JP
//        // iOS10注册方法
//        let entity = JPUSHRegisterEntity()
//        entity.types = Int(UNAuthorizationOptions.alert.rawValue |
//            UNAuthorizationOptions.badge.rawValue |
//            UNAuthorizationOptions.sound.rawValue)
//        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
//        #if APPSTORE
//            JPUSHService.setup(withOption: launchOptions,
//                               appKey: "509c70b8c37f1bb451a58e4c",
//                               channel: "App Store",
//                               apsForProduction: true)
//        #else
//            #if DEBUG
//                JPUSHService.setup(withOption: launchOptions,
//                                   appKey: "509c70b8c37f1bb451a58e4c",
//                                   channel: "App Store",
//                                   apsForProduction: false)
//            #else
//                JPUSHService.setup(withOption: launchOptions,
//                                   appKey: "509c70b8c37f1bb451a58e4c",
//                                   channel: "App Store",
//                                   apsForProduction: true)
//            #endif
//
//        #endif
//        JPUSHService.crashLogON()
//
//        unreadCount = UserDefaults.standard.integer(forKey: CDUserDefaultKey.jpushRedPointValueCountKey)
//
//        // 注册 透传消息通知
//        NotificationCenter.default.addObserver(self, selector: #selector(networkDidReceiveMessage(_:)), name: NSNotification.Name.jpfNetworkDidReceiveMessage, object: nil)
//    }
//
//    deinit {
//        NotificationCenter.default.removeObserver(self)
//    }
//
//
//    func networkDidReceiveMessage(_ notification: Notification) {
//        // 透传消息
//        /*
//         NSDictionary *userInfo = [notification userInfo];
//         NSDictionary *extras = [userInfo valueForKey:@"extras"];
//         NSString *myselfToken = [MySelfSingleton sharedInstance].token;
//         */
//    }
//
//    func setTagsAndAlias() {
//        guard let userID = MyselfSingleton.shared.userInfo?.userID else {
//            return
//        }
//        if userID.isEmpty {
//            return
//        }
//
//        JPUSHService.setAlias(userID, completion: { (code, alias, seq) in
//            if code == 0
//            {
//                // success
//            }
//        }, seq: 100)
//
//        JPUSHService.setTags(Set(["iOS"]), completion: { (code, alias, seq) in
//        }, seq: 100)
//    }
//
//    func cleanTagsAndAlias() {
////        JPUSHService.setAlias("", completion: nil, seq: 0)
//        JPUSHService.deleteAlias(nil, seq: 10086)
//        JPUSHService.setTags(Set(), completion: nil, seq: 0)
////        + (void)clearTagsAndAlias
////            {
////                [JPUSHService setTags:[NSSet set] alias:@"" callbackSelector:nil object:nil];
////        }
//
//    }
//
//
//    /* 红点计数
//     * count: 极光消息未读数
//     */
//    func configUnreadCount(_ count: Int) {
//        UserDefaults.standard.set(count, forKey: CDUserDefaultKey.jpushRedPointValueCountKey)
//        let newCount = count + CDIMService.shared.unreadCount()
//        if !JPUSHService.setBadge(newCount)
//        {
//            CDUtility.log("JPUSHService 设置角标失败！！！！！setBadge newCount:\(newCount)")
//        }
//    }
//
//}
//
//extension CDPushService
//{
//    func tabbarLaunched() {
//        // 消息
//        if !preChatUserID.isEmpty
//        {
//            preUserInfo.removeAll()
//            jumpToMessagePage(preChatUserID)
//            return
//        }
//        // 极光推送
//        if !preUserInfo.isEmpty
//        {
//            handleJpushPageJump(preUserInfo)
//        }
//    }
//
//    // IM Jump
//    func jumpToMessagePage(_ userID: String) {
//        preChatUserID = ""
//        guard let myID = MyselfSingleton.shared.userInfo?.userID,!myID.isEmpty else { return  }
//        guard let currentViewController = CDUtility.currentViewController() else {
//            preChatUserID = userID
//            return
//        }
//        if currentViewController.presentingViewController == UIManager.shared.tabBarController
//        {
//            currentViewController.dismiss(animated: false, completion: {
//                DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.2, execute: {
//                    self.jumpToMessagePage(userID)
//                })
//            })
//        }
//
//
//        if let messageViewController = currentViewController as? MessageViewController,messageViewController.session.sessionId == userID
//        {
//            // 啥事也不做
//        }
//        else
//        {
//            let session = NIMSession(userID, type: .P2P)
//            let chatModel = ChatModel.init(session, chatName: "", sessionID: session.sessionId, chatAvatar: "", isFirstTalk: false, dataState: .done)
//            RouterManager.shared.openPage(currentViewController: currentViewController, toVC: ControllerName.messageChat, parameter: ["chatModel":chatModel as Any])
//
////            if let messageNavigationController = UIManager.shared.tabBarController.viewControllers![TabBarIndex.messageList.rawValue] as? MessageNavigationController
////            {
////                if let messageListViewController = messageNavigationController.viewControllers.first as? MessageListViewController
////                {
////                    let session = NIMSession(userID, type: .P2P)
////                    let chatModel = ChatModel.init(session, chatName: "", sessionID: session.sessionId, chatAvatar: "", isFirstTalk: false)
////                    messageListViewController.chatModel = chatModel
////                    if let nav = currentViewController.navigationController,!(nav is LoginNavigationController)
////                    {
////                        if currentViewController.navigationController! == messageNavigationController
////                        {
////                            currentViewController.navigationController?.navigationBar.isHidden = false
////                            currentViewController.navigationController?.popToRootViewController(animated: true)
////                        }
////                        else
////                        {
////                            UIManager.shared.tabBarController.selectedIndex = TabBarIndex.messageList.rawValue
////                            currentViewController.navigationController?.popToRootViewController(animated: false)
////                        }
////                    }
////                }
////            }
//        }
//    }
//
//    // 极光的页面跳转
//    func handleJpushPageJump(_ userInfo: [String : AnyObject]) {
//        guard let type = userInfo["type"] as? String,!type.isEmpty else { return }
//        guard let myID = MyselfSingleton.shared.userInfo?.userID,!myID.isEmpty else { return  }
//
//        preUserInfo.removeAll()
//        guard let currentViewController = CDUtility.currentViewController() else {
//            preUserInfo = userInfo
//            return
//        }
//        if currentViewController.presentingViewController == UIManager.shared.tabBarController
//        {
//            currentViewController.dismiss(animated: false, completion: {
//                DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1, execute: {
//                    self.handleJpushPageJump(userInfo)
//                })
//            })
//        }
//
////        if type == CDAPNSTypeNewFriends
////        {
////            if currentViewController is NewFriendsViewController
////            {
////                return
////            }
////            if let contactsNavigationController = UIManager.shared.tabBarController.viewControllers![TabBarIndex.contacts.rawValue] as? ContactsNavigationController
////            {
////                if let contactsViewController = contactsNavigationController.viewControllers.first as? ContactsViewController
////                {
////                    contactsViewController.shouldOpenMyInvitesPage = false
////                    contactsViewController.shouldOpenNewFriendsPage = true
////                    if let nav = currentViewController.navigationController,!(nav is LoginNavigationController)
////                    {
////                        if currentViewController.navigationController! == contactsNavigationController
////                        {
////                            currentViewController.navigationController?.navigationBar.isHidden = false
////                            currentViewController.navigationController?.popToRootViewController(animated: true)
////                        }
////                        else
////                        {
////                            UIManager.shared.tabBarController.selectedIndex = TabBarIndex.contacts.rawValue
////                            currentViewController.navigationController?.popToRootViewController(animated: false)
////                        }
////                    }
////                }
////            }
////        }
////        else if type == CDAPNSTypeMyInvite
////        {
////            if currentViewController is InviteRecordsViewController
////            {
////                return
////            }
////            if let contactsNavigationController = UIManager.shared.tabBarController.viewControllers![TabBarIndex.contacts.rawValue] as? ContactsNavigationController
////            {
////                if let contactsViewController = contactsNavigationController.viewControllers.first as? ContactsViewController
////                {
////                    contactsViewController.shouldOpenMyInvitesPage = true
////                    contactsViewController.shouldOpenNewFriendsPage = false
////                    if let nav = currentViewController.navigationController,!(nav is LoginNavigationController)
////                    {
////                        if currentViewController.navigationController! == contactsNavigationController
////                        {
////                            currentViewController.navigationController?.navigationBar.isHidden = false
////                            currentViewController.navigationController?.popToRootViewController(animated: true)
////                        }
////                        else
////                        {
////                            UIManager.shared.tabBarController.selectedIndex = TabBarIndex.contacts.rawValue
////                            currentViewController.navigationController?.popToRootViewController(animated: false)
////                        }
////                    }
////                }
////            }
////        }
////        else if type == CDAPNsTypeChatToUser
////        {
////            guard let userID = userInfo["userId"] as? String,!userID.isEmpty else { return }
////            jumpToMessagePage(userID)
////        }
//    }
//}
//
//extension CDPushService : JPUSHRegisterDelegate{
//    // 点开推送
//    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> ())!) {
//        let userInfo = response.notification.request.content.userInfo
////        let d = userInfo["aps"]
//        if let nim = userInfo["nim"] as? String,nim == "1"
//        { // 云信推送在云信的service处理
//            if let userID = userInfo["userID"] as? String,!userID.isEmpty
//            {
//                if let currentViewController = CDUtility.currentViewController(),currentViewController.presentingViewController == nil
//                {
//                    jumpToMessagePage(userID)
//                }
//                else
//                {
//                    preChatUserID = userID
//                }
//            }
//        }
//        else
//        { // 极光的推送
//            if let object = userInfo as? [String : AnyObject]
//            {
//                handleJpushPageJump(object)
//            }
//            if response.notification.request.trigger is UNPushNotificationTrigger
//            {
//                JPUSHService.handleRemoteNotification(userInfo)
//            }
//        }
//        completionHandler() // 系统要求执行这个方法
//    }
//
//    // 收到推送
//    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> ())!) {
//        let userInfo = notification.request.content.userInfo
//        if notification.request.trigger is UNPushNotificationTrigger
//        {
//            JPUSHService.handleRemoteNotification(userInfo)
//        }
//
//        if let nim = userInfo["nim"] as? String,nim == "1"
//        {
//        }
//        else
//        {
//            if let type = userInfo["type"] as? String,!type.isEmpty
//            {
//                if type == CDAPNSTypeMyInvite || type == CDAPNSTypeNewFriends
//                {
////                    let contactsViewController = UIManager.shared.tabBarController.contactsNavigationController.viewControllers.first as! ContactsViewController
////                    contactsViewController.needRefresh = true
////                    UIManager.shared.tabBarController.contactRedPointView.isHidden = false
////                    unreadCount += 1
////                    configUnreadCount(unreadCount)
////
////                    NotificationCenter.default.post(name: Notification.Name.CDContactNeedChangeUnreadCountNotificationKey, object: ["isNewFriend" : type == CDAPNSTypeNewFriends ])
//
//                }
//                else if type == CDAPNsTypeChatToUser
//                {
////                    let contactsViewController = UIManager.shared.tabBarController.contactsNavigationController.viewControllers.first as! ContactsViewController
////                    contactsViewController.needRefresh = true
//////                    UIManager.shared.tabBarController.contactRedPointView.isHidden = false
////                    unreadCount += 1
////                    configUnreadCount(unreadCount)
//                }
//            }
//        }
//        let type = Int(UNAuthorizationOptions.badge.rawValue |
////            UNAuthorizationOptions.alert.rawValue |
//            UNAuthorizationOptions.sound.rawValue)
//        completionHandler(type)  // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
//    }
//
//}
//
